<template>
  <RadModal
    :visible="visible"
    :loading="loading"
    :isUpdate="isUpdate"
    title="机构"
    @visible-change="updateVisible"
    @ok="save"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="styleResponsive ? { md: 4, sm: 5, xs: 24 } : { flex: '90px' }"
      :wrapper-col="
        styleResponsive ? { md: 19, sm: 19, xs: 24 } : { flex: '1' }
      "
    >
      <a-form-item label="上级机构" name="pid">
        <a-tree-select
          allow-clear
          tree-default-expand-all
          placeholder="请选择上级机构"
          v-model:value="form.pid"
          :fieldNames="{ label: 'name', value: 'id' }"
          :tree-data="orglist"
          :dropdown-style="{ maxHeight: '360px', overflow: 'auto' }"
        />
      </a-form-item>
      <a-form-item label="机构名称" name="name">
        <a-input
          allow-clear
          :maxlength="20"
          placeholder="请输入机构名称"
          v-model:value="form.name"
        />
      </a-form-item>
      <a-form-item label="机构代码" name="code">
        <a-input
          allow-clear
          :maxlength="20"
          placeholder="请输入机构代码"
          v-model:value="form.code"
        />
      </a-form-item>

      <a-form-item label="排序号" name="order">
        <a-input-number
          :min="0"
          :max="99999"
          class="ele-fluid"
          placeholder="请输入排序号"
          v-model:value="form.order"
        />
      </a-form-item>
      <a-form-item label="状态" name="status">
        <a-radio-group
          size="default"
          v-model:value="form.status"
          button-style="solid"
        >
          <a-radio-button :value="1">启用</a-radio-button>
          <a-radio-button :value="2">停用</a-radio-button>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="备注">
        <a-textarea
          :rows="4"
          :maxlength="200"
          placeholder="请输入备注"
          v-model:value="form.remark"
        />
      </a-form-item>
    </a-form>
  </RadModal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { message } from 'ant-design-vue/es';
  import type { FormInstance, Rule } from 'ant-design-vue/es/form';
  import { storeToRefs } from 'pinia';
  import { useThemeStore } from '@/store/modules/theme';
  import useFormData from '@/utils/use-form-data';
  import { add, update } from '@/api/system/dataResource';
  import RadModal from '@/components/RadModal/index.vue';
  import { SysDataResource } from '@/api/system/dataResource/model';

  // 是否开启响应式布局
  const themeStore = useThemeStore();
  const { styleResponsive } = storeToRefs(themeStore);

  const emit = defineEmits<{
    (e: 'done', isUpdate: boolean, data: object): void;
    (e: 'update:visible', visible: boolean): void;
  }>();

  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 修改回显的数据
    data?: SysDataResource | null;
    //组织架构数据
    orglist: SysDataResource[];
  }>();

  //
  const formRef = ref<FormInstance | null>(null);

  // 是否是修改
  const isUpdate = ref(false);

  // 提交状态
  const loading = ref(false);

  // 表单数据
  const { form, resetFields, assignFields } = useFormData<SysDataResource>({
    id: 0,
    pid: 0,
    name: '',
    code: '',
    order: 100,
    status: 1,
    remark: ''
  });

  // 表单验证规则
  const rules = reactive<Record<string, Rule[]>>({
    name: [
      {
        required: true,
        message: '请输入机构名称',
        type: 'string',
        trigger: 'blur'
      }
    ],
    code: [
      {
        required: true,
        message: '请输入机构标识',
        type: 'string',
        trigger: 'blur'
      }
    ],
    order: [
      {
        required: true,
        message: '请输入排序号',
        type: 'number',
        trigger: 'blur'
      }
    ]
  });

  /* 保存编辑 */
  const save = () => {
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        const orgData = {
          ...form,
          parentId: form.pid || 0
        };
        const saveOrUpdate = isUpdate.value ? update : add;
        saveOrUpdate(orgData)
          .then((msg) => {
            loading.value = false;
            message.success(msg);
            updateVisible(false);
            emit('done', isUpdate.value, form);
          })
          .catch((e) => {
            loading.value = false;
            message.error(e.message);
          });
      })
      .catch(() => {});
  };

  /* 更新visible */
  const updateVisible = (value: boolean) => {
    emit('update:visible', value);
  };

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        if (props.data) {
          assignFields(props.data);
          isUpdate.value = true;
        } else {
          isUpdate.value = false;
        }
      } else {
        resetFields();
        formRef.value?.clearValidate();
      }
    }
  );
</script>
